const entryObj=require('./entries.js');//引入入口对象
const webpackBaseConfig = require('./webpack.base.js');//引入webpack基本配置
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//将CSS提取到单独的文件中
const portfinder = require('portfinder');//引入寻找可用端口插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');//引入友好错误提升插件
const notifier = require('node-notifier');//引入node 提示插件
const { merge } = require('webpack-merge');//引入参数合并loader

const webpackDevConfig = merge(webpackBaseConfig, {
  mode: 'development',//打包模式
  devtool: 'cheap-module-eval-source-map',//开发工具
  module: {},
  plugins: [//插件
    new MiniCssExtractPlugin({
      filename: 'pages/[name]/index.css',
      chunkFilename: 'pages/[name]/index.chunk.css'
    }),
  ],
  devServer: {//开发服务
    clientLogLevel: 'warning',
    contentBase: false,//启动目录
    open: true,//自动打开浏览器
    compress: true,//gzip压缩
    overlay: { warnings: false, errors: true },
    quiet: true,
    host: entryObj.getIPAdress() || '0.0.0.0',
    proxy: {
      '/api': {
        target: entryObj.url,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  output: {//出口配置
    filename: 'pages/[name]/index.js',//打包好的文件存放目录和名称
    chunkFilename: 'pages/[name]/index.chunk.js',
  }
});

module.exports = new Promise((resolve, reject) => {
  portfinder.getPort((err, port) => {//获取可用端口
    if (err) {
      reject(err);
    } else {
      webpackDevConfig.devServer.port = port;//将找到的端口赋值到devServer.port上
      webpackDevConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`项目运行在这里: http://${entryObj.getIPAdress()}:${port}`],
        },
        onErrors: function (severity, errors) {
          if (severity == 'error') {
            notifier.notify({
              title: '警告!',
              message: '运行出错!'
            })
          } else {
            return;
          }
        }
      }))
      resolve(webpackDevConfig)
    }
  });
});
